<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录接口详细测试</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 600px; margin: 0 auto; }
        h1 { color: #333; }
        .input-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input { width: 100%; padding: 8px; box-sizing: border-box; }
        button { padding: 10px 15px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        button:hover { background-color: #45a049; }
        .result { margin-top: 20px; padding: 15px; border: 1px solid #ddd; background-color: #f9f9f9; }
        pre { white-space: pre-wrap; word-wrap: break-word; }
        .status { font-weight: bold; padding: 5px; border-radius: 3px; }
        .success { color: green; }
        .error { color: red; }
    </style>
</head>
<body>
    <div class="container">
        <h1>登录接口详细测试工具</h1>
        
        <div class="input-group">
            <label for="backendUrl">后端URL:</label>
            <input type="text" id="backendUrl" value="http://localhost:8000" placeholder="输入后端服务地址">
        </div>
        
        <div class="input-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" value="admin" placeholder="输入用户名">
        </div>
        
        <div class="input-group">
            <label for="password">密码:</label>
            <input type="password" id="password" value="123456" placeholder="输入密码">
        </div>
        
        <button onclick="testLogin()">测试登录</button>
        <button onclick="clearResults()">清空结果</button>
        
        <div class="result" id="result">
            <h3>测试结果:</h3>
            <div id="logs"></div>
        </div>
    </div>

    <script>
        const logsElement = document.getElementById('logs');
        
        function log(message, type = 'info') {
            const logEntry = document.createElement('div');
            logEntry.innerHTML = `<strong>[${new Date().toLocaleTimeString()}]</strong> ${message}`;
            if (type === 'success') {
                logEntry.className = 'status success';
            } else if (type === 'error') {
                logEntry.className = 'status error';
            }
            logsElement.appendChild(logEntry);
            logsElement.scrollTop = logsElement.scrollHeight;
        }
        
        function logJSON(data, prefix = '') {
            const pre = document.createElement('pre');
            pre.textContent = `${prefix} ${JSON.stringify(data, null, 2)}`;
            logsElement.appendChild(pre);
        }
        
        function clearResults() {
            logsElement.innerHTML = '';
        }
        
        async function testLogin() {
            clearResults();
            
            const backendUrl = document.getElementById('backendUrl').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            log(`开始测试登录 - 用户名: ${username}`);
            log(`后端URL: ${backendUrl}`);
            
            // 测试网络连接
            try {
                log('测试网络连接...');
                const pingStart = performance.now();
                const pingResponse = await axios.get(`${backendUrl}/health`, { timeout: 3000 });
                const pingEnd = performance.now();
                log(`网络连接成功! 响应时间: ${(pingEnd - pingStart).toFixed(2)}ms`, 'success');
                logJSON(pingResponse.data, '健康检查响应:');
            } catch (pingError) {
                log(`网络连接失败: ${pingError.message}`, 'error');
                if (pingError.response) {
                    logJSON(pingError.response.data, '错误详情:');
                }
                return;
            }
            
            // 准备登录数据
            const formData = new URLSearchParams();
            formData.append('username', username);
            formData.append('password', password);
            
            log('准备发送登录请求...');
            log(`请求数据: ${formData.toString()}`);
            
            try {
                const loginStart = performance.now();
                const loginResponse = await axios.post(`${backendUrl}/auth/login`, formData, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    withCredentials: true,
                    timeout: 5000
                });
                const loginEnd = performance.now();
                
                log(`登录请求成功! 响应时间: ${(loginEnd - loginStart).toFixed(2)}ms`, 'success');
                logJSON(loginResponse.data, '登录响应:');
                
                if (loginResponse.data.access_token) {
                    log('获取访问令牌成功，尝试访问受保护资源...');
                    
                    try {
                        const meStart = performance.now();
                        const meResponse = await axios.get(`${backendUrl}/auth/me`, {
                            headers: {
                                'Authorization': `Bearer ${loginResponse.data.access_token}`
                            },
                            withCredentials: true,
                            timeout: 5000
                        });
                        const meEnd = performance.now();
                        
                        log(`访问用户信息成功! 响应时间: ${(meEnd - meStart).toFixed(2)}ms`, 'success');
                        logJSON(meResponse.data, '用户信息:');
                        log('✅ 完整测试流程成功!', 'success');
                    } catch (meError) {
                        log(`访问用户信息失败: ${meError.message}`, 'error');
                        if (meError.response) {
                            logJSON(meError.response.data, '错误详情:');
                        }
                    }
                }
            } catch (loginError) {
                log(`登录请求失败: ${loginError.message}`, 'error');
                if (loginError.response) {
                    log(`HTTP状态码: ${loginError.response.status}`);
                    logJSON(loginError.response.data, '错误详情:');
                } else if (loginError.request) {
                    log('没有收到服务器响应，请检查网络连接和服务器状态', 'error');
                } else {
                    log(`请求配置错误: ${loginError.message}`, 'error');
                }
                
                // 显示可能的解决方案
                log('\n可能的解决方案:', 'info');
                log('1. 确保后端服务正在http://localhost:8000运行');
                log('2. 检查用户名和密码是否正确 (默认admin/123456)');
                log('3. 检查是否有CORS相关问题');
                log('4. 检查浏览器控制台是否有更详细的错误信息');
            }
        }
    </script>
</body>
</html>